#!/usr/bin/env bash

# Copyright 2018, Rackspace US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# {{ ansible_managed }}

set -e

{{ nspawn_cache_prep_pre_commands }}

{% include 'templates/prep-scripts/_container_sys_setup.sh.j2' %}

# We have (tried to!) copied repo-oss and repo-update from the host so wipe everything else.
find /etc/zypp/repos.d/ -type f ! -name "repo-oss.repo" -a ! -name "repo-update.repo" -delete
zypper lr | grep -q 'repo-oss' || zypper --quiet ar {{ nspawn_hosts_opensuse_mirror_url }}/distribution/leap/{{ ansible_distribution_version }}/repo/oss repo-oss
zypper lr | grep -q 'repo-update' || zypper --quiet ar {{ nspawn_hosts_opensuse_mirror_url }}/update/leap/{{ ansible_distribution_version }}/oss repo-update

# Disable recommended packages. Only update what's really needed
if ! fgrep -qx "solver.onlyRequires = true" /etc/zypp/zypp.conf; then
    echo -e "\n\n## Disable recommended packages\nsolver.onlyRequires = true" >> /etc/zypp/zypp.conf
fi

# Key import
zypper --gpg-auto-import-keys -n dup --force-resolution -l
zypper --gpg-auto-import-keys -n in --force-resolution -l {{ (nspawn_container_distro_packages | union(nspawn_container_distro_required_packages) | unique) | join(' ') }}

rm -f /usr/bin/python || true
ln -s /usr/bin/python2.7 /usr/bin/python

for action in disable; do
  systemctl ${action} wicked.service || true
  systemctl ${action} wickedd.service || true
  systemctl ${action} wickedd-auto4.service || true
  systemctl ${action} wickedd-dhcp4.service || true
  systemctl ${action} wickedd-dhcp6.service || true
  systemctl ${action} wickedd-nanny.service || true
  systemctl ${action} sshd.service || true
done

systemctl enable systemd-hostnamed.service
systemctl enable systemd-networkd.service

userdel --force --remove opensuse || true

{{ nspawn_cache_prep_post_commands }}
